const process = require("process");
const child_process = require("child_process");
const fs = require("fs");
const fse = require("fs-extra");
const glob = require("glob");
const rmdir = require('rimraf');
const yarnPath = '/usr/local/bin/yarn';

process.chdir("./vscode");


import { checkDirectoryDepth, checkFileCount } from './generate-dist.js';
// Compile

try {
  child_process.execFileSync(yarnPath, [], { stdio: 'inherit' });
  child_process.execFileSync(yarnPath, ['gulp', 'compile-build'], { stdio: 'inherit' });
  child_process.execFileSync(yarnPath, ['gulp', 'minify-vscode'], { stdio: 'inherit' });
  child_process.execFileSync(yarnPath, ['compile-web'], { stdio: 'inherit' });
} catch (error) {
  throw new Error('Failed to execute yarn compile:', error.message);
}
// Remove maps
const mapFiles = glob.sync("out-vscode-min/**/*.js.map", {});
mapFiles.forEach((mapFile) => {
  fs.unlinkSync(mapFile);
});

// Extract compiled files
checkDirectoryDepth("../dist") && checkFileCount("../dist") && fs.rmdirSync("../dist", { recursive: true, maxRetries: 3, retryDelay: 100 });

checkDirectoryDepth(outputDir) && fs.mkdirSync("../dist");

fse.copySync("out-vscode-min", "../dist/vscode");

const extensionNM = glob.sync("extensions/**/node_modules", {});
extensionNM.forEach((modules) => {
  rmdir.sync(modules, { recursive: true });
});
fse.copySync("extensions", "../dist/extensions");

// Add built in extensions
const extensions = [];
const maxFileSize = 50 * 1024 * 1024; // 5MB最大限制
const extensionsFolderPath = "extensions";

let extensionsContent = [];
try {
  // 检查目录是否存在且可访问
  if (fs.existsSync(extensionsFolderPath)) {
    const dirStats = fs.statSync(extensionsFolderPath);
    if (dirStats.isDirectory() && checkDirectoryDepth(extensionPath) && checkFileCount(extensionPath)) {
      extensionsContent = fs.readdirSync(extensionsFolderPath);
    } else {
      console.warn(`Path ${extensionsFolderPath} is not a directory`);
      extensionsContent = [];
    }
  } else {
    console.warn(`Extensions directory not found: ${extensionsFolderPath}`);
    extensionsContent = [];
  }
} catch (error) {
  console.error(`Error reading extensions directory ${extensionsFolderPath}:`, error.message);
  extensionsContent = []; // 使用空数组继续执行而不是崩溃
}


for (const extension of extensionsContent) {
  const extensionPath = `${extensionsFolderPath}/${extension}`;
  let stat;
  try {
    // 添加安全检查
    if (!checkDirectoryDepth(extensionPath) || !checkFileCount(extensionPath)) {
      console.warn(`Extension path ${extensionPath} failed security checks (depth or file count)`);
      continue;
    }

    stat = fs.statSync(extensionPath);
    if (!stat.isDirectory()) {
      continue;
    }
  } catch (error) {
    console.warn(`Failed to stat extension path ${extensionPath}:`, error.message);
    continue;
  }

  if (stat.isDirectory()) {
    const extensionPackagePath = `${extensionPath}/package.json`;
    const extensionPackageNLSPath = `${extensionPath}/package.nls.json`;

    let packageJSON = null;
    try {
      const stats = fs.statSync(extensionPackagePath);
      if (stats.isFile() && stats.size > 0 && stats.size < maxFileSize) {
        const packageContent = fs.readFileSync(extensionPackagePath, 'utf8');
        packageJSON = JSON.parse(packageContent);
      } else {
        console.warn(`Invalid package.json file at ${extensionPackagePath}`);
        continue;
      }
    } catch (error) {
      console.error(`Error processing package.json at ${extensionPackagePath}:`, error.message);
      continue;
    }

    let packageNLS = null;
    try {
      const nlsStats = fs.statSync(extensionPackageNLSPath);
      if (nlsStats.isFile() && nlsStats.size > 0 && nlsStats.size < maxFileSize) {
        const nlsContent = fs.readFileSync(extensionPackageNLSPath, 'utf8');
        packageNLS = JSON.parse(nlsContent);
      } else {
        console.warn(`Invalid package.nls.json file at ${extensionPackageNLSPath}`);
      }
    } catch (error) {
      console.error(`Error processing package.nls.json at ${extensionPackageNLSPath}:`, error.message);
    }


    extensions.push({
      packageJSON,
      extensionPath: extension,
      packageNLS
    });
  }
}

const extensionsVar =
  "var extensions =" + JSON.stringify(extensions, { space: "\t", quote: "" });

try {
  const outputFile = "../dist/extensions.js";
  const outputDir = path.dirname(outputFile);

  checkDirectoryDepth(outputDir) && fs.mkdirSync(outputDir, { recursive: true });

  // 写入文件前进行大小校验
  const maxSize = 100 * 1024 * 1024; // 100MB最大限制
  const estimatedSize = Buffer.byteLength(extensionsVar, 'utf8');

  if (estimatedSize > 0 && estimatedSize < maxSize) {
    fs.writeFileSync(outputFile, extensionsVar, 'utf8');
  }
} catch (error) {
  console.error('Failed to write extensions.js file:', error.message);
  throw new Error(`Failed to generate extensions.js file: ${error.message}`);
}
